package com.alks.function.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import com.alks.common.aop.AutoPageAop;
import com.alks.common.data.dto.SysUserTokenDTO;
import com.alks.common.data.thread.UserIdThread;
import com.alks.common.service.RedisService;
import com.alks.common.utils.DateUtils;
import com.alks.common.utils.QRCodeGenerator;
import com.alks.common.utils.excelUtils.ExcelPoiUtils;
import com.alks.common.utils.excelUtils.ExcelUtils;
import com.alks.entity.data.entity.*;
import com.alks.entity.data.response.ResponseInfo;
import com.alks.entity.exception.ServiceErrorException;
import com.alks.function.data.dto.*;
import com.alks.function.data.dto.chengKong.assort.SdCustTypeDto;
import com.alks.function.data.dto.chengKong.assort.SdMtlTypeNewDto;
import com.alks.function.data.request.MaterialLotRequest;
import com.alks.function.data.request.MaterialOutRequest;
import com.alks.function.data.request.MaterialRequest;
import com.alks.function.data.request.last.OutsoleOrderDetailReq;
import com.alks.function.data.request.operate.material.GeneralMaterialRequest;
import com.alks.function.data.request.operate.material.MaterialDetail1Request;
import com.alks.function.data.request.order.PcOrderMtlRegularSingleRequest;
import com.alks.function.data.request.stock.*;
import com.alks.function.mapper.MaterialMapper;
import com.alks.function.mapper.PcOrderHeadMapping;
import com.alks.function.mapper.SdCompanyMapper;
import com.alks.function.service.MaterialService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.zxing.WriterException;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.support.atomic.RedisAtomicInteger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import static com.alks.entity.data.enums.RedisFormatEnum.*;

@Slf4j
@Service
public class MaterialServiceImpl implements MaterialService {

    @Autowired
    private MaterialMapper materialMapper;

    @Autowired
    private SdCompanyMapper sdCompanyMapper;

    /**
     * 材料入库明细
     *
     * @param request
     * @return
     */
    @Override
    @AutoPageAop
    public ResponseInfo getInventoryDetail(MaterialRequest request) {

        //公司
        String companyId = UserIdThread.get().getCompanyId();
        request.setCompanyId(companyId);
        String userId = UserIdThread.get().getUserId();
        Map map = new HashMap();

        //入库明细查询
        List<MaterialDto> inventoryDetails = materialMapper.getInventoryDetails(request);
        for (MaterialDto inventoryDetail : inventoryDetails) {
            if ("Y".equals(inventoryDetail.getACheckFlag())) {
                inventoryDetail.setACheckFlag("合格");
            }
            if ("N".equals(inventoryDetail.getACheckFlag())) {
                inventoryDetail.setACheckFlag("不合格");
            }
            if ("Y".equals(inventoryDetail.getPCheckFlag())) {
                inventoryDetail.setPCheckFlag("合格");
            }
            if ("N".equals(inventoryDetail.getPCheckFlag())) {
                inventoryDetail.setPCheckFlag("不合格");
            }
            if (!"LMN".equals(userId) && !"LMNHF".equals(userId)) {
                inventoryDetail.setPrice(0);
                inventoryDetail.setAmt(BigDecimal.ZERO);
            }

        }

        //拿到total
        PageInfo list = new PageInfo(inventoryDetails);

        //入库明细统计总数
        MaterialCountDto detailsCount = materialMapper.getInventoryDetailsList(request);

        map.put("inventoryDetails", inventoryDetails);
        map.put("total", list.getTotal());
        map.put("detailsCount", detailsCount);
        return ResponseInfo.ok(map);
    }

    /**
     * 材料入库指令明细
     *
     * @param request
     * @return
     */
    @Override
    public ResponseInfo getLotDetailInfo(MaterialLotRequest request) {

        //公司
        String companyId = UserIdThread.get().getCompanyId();
        request.setCompanyId(companyId);

        Map map = new HashMap();

        //指令明细
        List<MaterialLotDto> lotDetailList = materialMapper.getLotDetailList(request);

        //指令明细总数量
        MaterialLotCountDto count = materialMapper.getLotDetailListCount(request);

        map.put("lotDetailList", lotDetailList);
        map.put("count", count);

        return ResponseInfo.ok(map);
    }

    /**
     * 材料入库导出
     * @param request
     * @param response
     */
    @Override
    public void exportMaterial(MaterialRequest request, HttpServletResponse response) {
        //公司
        String companyId = UserIdThread.get().getCompanyId();
        request.setCompanyId(companyId);
        List<MaterialDto> list = materialMapper.getInventoryDetails(request);
        if (ObjectUtils.isEmpty(list)) {
            throw new ServiceErrorException("查询数据为空!");
        }
        String fileName = "材料入库明细" + DateUtils.dateTimeNow() + ".xlsx";
        Map<String, Object> map = new HashMap<>();
        map.put("date", LocalDate.now());
        SdCompany sdCompany = sdCompanyMapper.findAllBYCompanyId(UserIdThread.get().getCompanyId());
        map.put("name", sdCompany.getAbbrName());
        try (
                InputStream inputStream = new ClassPathResource("templates/材料入库明细模板.xlsx").getInputStream();
                OutputStream outputStream = response.getOutputStream();
                ExcelWriter excelWriter = EasyExcel.write(outputStream).excelType(ExcelTypeEnum.XLSX).withTemplate(inputStream).build();
        ) {
            ExcelUtils.setResponseZF(response, fileName);
            WriteSheet sheet1 = EasyExcel.writerSheet().build();
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
            excelWriter.fill(new FillWrapper("t", list), fillConfig, sheet1);
            excelWriter.fill(map, fillConfig, sheet1);
            excelWriter.finish();
        } catch (Exception e) {
            log.error("材料入库明细表导出失败, 错误信息: {}", e.getMessage(), e);
            throw new ServiceErrorException("材料入库明细表导出失败!");
        }
    }

    /**
     * 材料出库领料明细
     *
     * @param request
     * @return
     */
    @Override
    @AutoPageAop
    public ResponseInfo getMaterialDetailOut(MaterialOutRequest request) {
        Map map = new HashMap();
        List<MaterialOutDto> materialDetailOutList = materialMapper.getMaterialDetailOutList(request);
        PageInfo list = new PageInfo(materialDetailOutList);

        map.put("materialDetailOutList", materialDetailOutList);
        map.put("total", list.getTotal());
        return ResponseInfo.ok(map);
    }

    /**
     * 材料出库实发明细
     *
     * @param request
     * @return
     */
    @Override
    public ResponseInfo getSendOutList(MaterialLotRequest request) {
        Map map = new HashMap();
        List<MaterialSendOutDto> sendList = materialMapper.getSendList(request);
        BigDecimal sendCount = materialMapper.getSendCount(request);
        map.put("sendList", sendList);
        map.put("sendCount", sendCount);
        return ResponseInfo.ok(map);
    }

    /**
     * 出库明细导出
     * @param request
     * @param response
     */
    @Override
    public void exportMaterialDetailOut(MaterialOutRequest request, HttpServletResponse response) {
         List<MaterialOutDto> list = materialMapper.getMaterialOutList(request);
         if (ObjectUtils.isEmpty(list)){
             throw new ServiceErrorException("查询数据为空!");
         }
        for (MaterialOutDto t : list) {
            if (!ObjectUtils.isEmpty(t)){
                double price=t.getPrice();
                double actQty = t.getActQty() != null ? t.getActQty().doubleValue() : 0;
                if (actQty!=0){
                    price=actQty*price;
                    t.setAmt(price);
                }else {
                    t.setAmt(0);
                }
            }
        }
        String fileName = "领料明细_" + DateUtils.dateTimeNow() + ".xlsx";
        try (
                InputStream inputStream = new ClassPathResource("templates/领料明细模板.xlsx").getInputStream();
                OutputStream outputStream = response.getOutputStream();
                ExcelWriter excelWriter = EasyExcel.write(outputStream).excelType(ExcelTypeEnum.XLSX).withTemplate(inputStream).build();
        ) {
            ExcelUtils.setResponseZF(response, fileName);
            WriteSheet sheet1 = EasyExcel.writerSheet().build();
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
            excelWriter.fill(new FillWrapper("t", list), fillConfig, sheet1);
            excelWriter.finish();
        } catch (Exception e) {
            log.error("领料明细表导出失败, 错误信息: {}", e.getMessage(), e);
            throw new ServiceErrorException("领料明细表导出失败!");
        }
    }

    @AutoPageAop
    @Override
    public ResponseInfo pcOrderMtlRS(PcOrderMtlRegularSingleRequest request) {
        Map<String, Object> map = new HashMap();
        List<PcOrderMtlRegularSingleRep> list = materialMapper.pcOrderMtlRS(request);
        map.put("list", list);
        Page<PcOrderMtlRegularSingleRep> page = (Page<PcOrderMtlRegularSingleRep>) list;
        map.put("total", page.getTotal());
        return ResponseInfo.ok(map);
    }

    @Override
    @AutoPageAop
    public ResponseInfo pcOrderMtlSo(PcOrderMtlRegularSingleRequest request) {
        Map<String, Object> map = new HashMap();
        List<PcOrderMtlRegularSingleRep> list = materialMapper.pcOrderMtlSo(request);
        map.put("list", list);
        Page<PcOrderMtlRegularSingleRep> page = (Page<PcOrderMtlRegularSingleRep>) list;
        map.put("total", page.getTotal());
        return ResponseInfo.ok(map);
    }

    @Autowired
    RedisService redisService;

    @Override
    @Transactional
    public ResponseInfo pcOrderMtlMakeOrder(PcOrderMtlRegularSingleOutRequest request) {
        //获取当前账号的用户名
        List<PcOrderMtlRegularSingleRep> list = request.getList();
        SysUserTokenDTO dto = UserIdThread.get();
        String sysUser = dto.getUserName();
        for (PcOrderMtlRegularSingleRep rep : list) {
            String lotNo = rep.getLotNo();
            String sizeNo = materialMapper.getSizeNo(lotNo);
            rep.setCompanyId(dto.getCompanyId());
            rep.setSizeNo(sizeNo);
        }
        if (request.getMark() != null && "1".equals(request.getMark())) {
            //面材
            materialMapper.pcOrderMtlMakeOrder(list, sysUser);
            materialMapper.pcOrderMtlMakeOrderPurDetail(list, sysUser);
        } else if (request.getMark() != null && "2".equals(request.getMark())) {
            //面材备料
            materialMapper.pcOrderMtlMakeOrderPre(list, sysUser);
            materialMapper.pcOrderMtlMakeOrderPrePurDetail(list, sysUser);
        }
        //添加到PC_MTL_PRE_OTHER
        //COMPANY_ID PUR_DATE MTL_NO MTL_NAME MTL_SPEC MTL_UNIT MTL_COLOR PUR_QTY  SYS_USER SYS_DATE REMARK ORDER_ID SIZE_NO STYLE PUR_TYPE判断是否为1 1面材 2面材补单
        //添加到PC_PUR_DETAIL

        //生成1 面材 2 备料 COMPANY_ID ORDER_ID PUR_TYPE 判断是否为1 1面材 2面材补单  MTL_NO MTL_NAME MTL_SPEC MTL_UNIT PUR_QTY REQ_DATE REMARK SYS_USER
        return ResponseInfo.ok("生成成功");
    }

    @Override
    public ResponseInfo pcOrderMtlMakeOrderDetail(PcOrderMaterialOrderDetailRequest request) {
        if (request.getPageNum() == null || request.getPageSize() == null) {
            request.setPageNum(1);
            request.setPageSize(10);
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize(), false);
        Map<String, Object> map = new HashMap<>();
        //获取当前账号用户名
        SysUserTokenDTO dto = UserIdThread.get();
        List<PcOrderMaterialOrderDetailRep> list = materialMapper.pcOrderMtlMakeOrderDetail(request, dto.getUserName());
        BigDecimal qtyTotal = materialMapper.pcOrderMtlMakeOrderDetailQtyTotal(request, dto.getUserName());
        BigDecimal purQtyTotal = materialMapper.pcOrderMtlMakeOrderDetailPurQtyTotal(request, dto.getUserName());
        Integer total = materialMapper.pcOrderMtlMakeOrderDetailTotal(request, dto.getUserName());
        map.put("list", list);
        map.put("qtyTotal", qtyTotal);
        map.put("purQtyTotal", purQtyTotal);
        map.put("total", total);
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo createPcOrderMtlOrder(PcOrderMtlOrderCreateRequest request) {
        //形成订购单号
        String userName = UserIdThread.get().getUserName();
        String purNo = "BFPM";
        String format = new SimpleDateFormat("yyyyMM").format(new Date());
        purNo = purNo + format;
        RedisAtomicInteger ato = new RedisAtomicInteger(format, redisService.getConnectionFactory());
        if (request.getCreateFlag() != null && "1".equals(request.getCreateFlag())) {
            try {
                if (request.getVendorName()==null) return ResponseInfo.error("厂商不能为空");
                if (request.getDeliveryDate()==null) return ResponseInfo.error("交期不能为空");
                //redis生成 订购单耗 设置订单号 设置厂商 交期 责任人 责任原因
                int increment = ato.getAndIncrement();
                //添加到PC_MTL_PRE_OTHER
                String num = String.format("%0" + PUT_PUR_LENGTH.getValue() + "d", increment);
                purNo = purNo + num;
                materialMapper.createPcOrderMtlOrder(request, purNo, userName);
                //形成订购单将pur_detail订购单号更新
            } catch (Exception e) {
                ato.decrementAndGet();
                return ResponseInfo.error("订购单号生成失败");
            }
            //添加到PC_PUR_DETAIL
            Map<String, Object> map = new HashMap<>();
            PcOrderMaterialOrderDetailRequest rep = new PcOrderMaterialOrderDetailRequest();
            rep.setPurNo(purNo);
            List<PcOrderMaterialOrderDetailRep> list = materialMapper.pcOrderMtlMakeOrderDetail(rep, userName);
            map.put("list", list);
            map.put("msg", "订购单号已形成");
            return ResponseInfo.ok(map);
        } else if (request.getCreateFlag() != null && "2".equals(request.getCreateFlag())) {
            int num = materialMapper.setNullPcOrderMtlOrder(request, userName);
            if (num <= 0) {
                return ResponseInfo.error("订购单号置空失败");
            }
            return ResponseInfo.ok("订购单号已置空");
        } else if (request.getCreateFlag() != null && "3".equals(request.getCreateFlag())) {
            PcOrderMaterialOrderDetailRep rep = request.getList().get(0);
            int num = materialMapper.updatePcOrderMtlOrder(rep, userName);
            if (num <= 0) {
                return ResponseInfo.error("修改失败");
            }
            return ResponseInfo.ok("修改成功");
        }else if ("4".equals(request.getCreateFlag())){
            materialMapper.deleteByList3(request,userName);
            return ResponseInfo.ok("删除成功");
        }
        return ResponseInfo.ok("createFlag不能为空且必需为 1、2、3");
    }

    @Override
    public ResponseInfo getMaterialADetail1(MaterialDetail1Request request) {
        if (request.getPageNum() == null || request.getPageSize() == null) {
            request.setPageNum(1);
            request.setPageSize(10);
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize(), false);
        Map<String, Object> map = new HashMap<>();
        SysUserTokenDTO dto = UserIdThread.get();
        String userName = dto.getUserName();
        List<PcOrderMaterToAllRep> list = materialMapper.getMaterialADetail1(request, userName);
        Integer total = materialMapper.getMaterialADetail1Total(request, userName);
        map.put("list", list);
        map.put("total", total);
        return ResponseInfo.ok(map);
    }

    @Override
    @Transactional
    public ResponseInfo updateMaterialADetail1(GeneralMaterialRequest request) {
        String username = UserIdThread.get().getUserName();
        List<PcOrderMaterToAllRep> list = request.getList();
        if (request.getChoose() != null && "1".equals(request.getChoose())) {
            //分类辅助生成
            for (PcOrderMaterToAllRep rep : list) {
                PcOrderPickingOperateDetailRep rep1 = new PcOrderPickingOperateDetailRep();
                rep1.setMtlName(rep.getMtlName());
                String mtlNo2 = pcOrderHeadMapping.getMtlTypeNo(rep1);
                if (mtlNo2!=null) rep.setMtlTypeNo(mtlNo2.substring(0, 4));
                if (mtlNo2==null){
                    String mtlTypeNo = pcOrderHeadMapping.getMtlTypeNoBy(rep1);
                    if (mtlTypeNo!=null) rep.setMtlTypeNo(mtlTypeNo);
                }
                int line = materialMapper.generalMaterial(rep, username);
            }
            return ResponseInfo.ok("生成成功");
        } else if (request.getChoose() != null && "2".equals(request.getChoose())) {
            //生成物料编码
            return creteMtlNo(list, username);
        } else if (request.getChoose() != null && "3".equals(request.getChoose())) {
            //置空物料编码
            return setNullMtlNO(list, username);
        } else if (request.getChoose() != null && "4".equals(request.getChoose())) {
            //形成订购单号
            return createPurNo(request, username);
        } else if (request.getChoose() != null && "5".equals(request.getChoose())) {
            //置空订购信息
            return setNullPurNo(request, username);
        } else if (request.getChoose() != null && "6".equals(request.getChoose())) {
            //打勾记录删除
            return deleteMtlNo(request, username);
        } else if (request.getChoose() != null && "7".equals(request.getChoose())) {
            //添加通用材料明细
            List<PcOrderMaterToAllRep> list1 = request.getList();
            if (list1==null) return ResponseInfo.error("前端自己检查");
            for (PcOrderMaterToAllRep rep : list1) {
                rep.setCompanyId(UserIdThread.get().getCompanyId());
                materialMapper.insertMaterial2(rep, username);
            }
            return ResponseInfo.ok("添加成功");
        } else if (request.getChoose() != null && ("8").equals(request.getChoose())) {
            PcOrderMaterToAllRep newRep = request.getList().get(0);
            PcOrderMaterToAllRep oldRep = request.getList().get(1);
            materialMapper.updateMaterial4(newRep, oldRep, username);
            return ResponseInfo.ok("修改成功");
        }
        return ResponseInfo.error("请检查choose参数是否为1、2、3、4、5、6、7");
    }

    private ResponseInfo deleteMtlNo(GeneralMaterialRequest request, String username) {
        //有订购单号不能删除 前端判断
        materialMapper.deleteByList2(request, username);
        return ResponseInfo.ok("删除成功");
    }

    private ResponseInfo setNullPurNo(GeneralMaterialRequest request, String userName) {
        materialMapper.setNullPcOrderMtlOrder2(request, userName);
        return ResponseInfo.ok("订购信息已置空");
    }

    private ResponseInfo createPurNo(GeneralMaterialRequest request, String username) {
        String purNo = getRedisAtomicInteger();
        if (request.getVendorName()==null || request.getDeliveryDate() == null) return ResponseInfo.error("厂商和订购单号不能为空");
        //前端需要判断物料编码以及采购数量不能为空
        for (PcOrderMaterToAllRep rep : request.getList()) {
            if (rep.getMtlNo() == null || rep.getMtlNo().isEmpty()) return ResponseInfo.error("物料编码不能为空");
            if (rep.getPurQty() == null) return ResponseInfo.error("采购数量不能为空");
        }
        materialMapper.createPcOrderMtlOrder2(purNo, request, username);
        MaterialDetail1Request req = new MaterialDetail1Request();
        req.setPurNo(purNo);
        List<PcOrderMaterToAllRep> list = materialMapper.getMaterialADetail1(req, username);
        Map<String,Object> map = new HashMap<>();
        map.put("list",list);
        map.put("msg","订购单号生成完成");
        return ResponseInfo.ok(map);
    }

    private ResponseInfo setNullMtlNO(List<PcOrderMaterToAllRep> list, String username) {
        int i = materialMapper.setMtlNoEmptyPickingOperate(list, username);
        if (i <= 0) {
            return ResponseInfo.error("置空失败。。。。请重试");
        }
        return ResponseInfo.ok("置空成功");
    }

    @Autowired
    private PcOrderHeadMapping pcOrderHeadMapping;

    private ResponseInfo creteMtlNo(List<PcOrderMaterToAllRep> list, String username) {
        for (PcOrderMaterToAllRep rep : list) {
            if (rep.getMtlName() == null || rep.getMtlName().isEmpty()) return ResponseInfo.error("物料名称不能为空");
            String mtlNo = pcOrderHeadMapping.getMtlNo(rep);
            if (mtlNo == null){
                String mtlTypeNo = rep.getMtlTypeNo();
                if (mtlTypeNo==null) return ResponseInfo.error("请先进行分类辅助生成");
                BigDecimal no2 = materialMapper.getMtlTypeNo2(mtlTypeNo);
                BigDecimal add = no2.add(new BigDecimal(1));
                int i = add.intValue();
                String mtlNo1 = String.format("%0" + PUT_MTL_LENGTH.getValue() + "d", i);
                mtlTypeNo = mtlTypeNo + mtlNo1;
                mtlNo = mtlTypeNo;
                rep.setCompanyId(UserIdThread.get().getCompanyId());
                rep.setMtlNo(mtlNo);
                materialMapper.insertIntoKf(rep,username);
            }
            //更新物料编码
            materialMapper.updateMaterial3(rep, mtlNo, username);
        }
        return ResponseInfo.ok("物料编码生成成功");
    }

    private String getRedisAtomicInteger() {
        String purNo = "BFPM";
        String format = new SimpleDateFormat("yyyyMM").format(new Date());
        purNo = purNo + format;
        RedisAtomicInteger ato = new RedisAtomicInteger(format, redisService.getConnectionFactory());
        int increment = ato.getAndIncrement();
        String num = String.format("%0" + PUT_PUR_LENGTH.getValue() + "d", increment);
        purNo = purNo + num;
        return purNo;
    }

    @AutoPageAop
    @Override
    public ResponseInfo getPcMtlMoldLot(PcMtlMoldLotRequest request) {
        Map<String, Object> map = new HashMap<>();
        if (request.getChoose() != null && "1".equals(request.getChoose())) {
            List<PcMtlMoldLotRep> list = materialMapper.getPcMtlMoldLot1(request);
            map.put("list", list);
            PageInfo page = new PageInfo(list);
            map.put("total", page.getTotal());
            return ResponseInfo.ok(map);
        } else if (request.getChoose() != null && "2".equals(request.getChoose())) {
            List<PcMtlMoldLotRep> list = materialMapper.getPcMtlMoldLot2(request);
            map.put("list", list);
            PageInfo page = new PageInfo(list);
            map.put("total", page.getTotal());
            return ResponseInfo.ok(map);
        }
        return ResponseInfo.error("前端传入choose参数为1、2");
    }

    @Override
    public ResponseInfo createPcMtlMoldLot(CreateMtlMoldRequest request) {
        String username = UserIdThread.get().getUserName();
        request.getList().forEach(x->x.setCompanyId(UserIdThread.get().getCompanyId()));
        if (request.getChoose() != null && "1".equals(request.getChoose())) {

            materialMapper.insertIntoMtlPre1(request, username);
            return ResponseInfo.ok("生成成功");
        } else if (request.getChoose() != null && "2".equals(request.getChoose())) {
            materialMapper.insertIntoMtlPre2(request, username);
            return ResponseInfo.ok("生成成功");
        }
        return ResponseInfo.error("choose参数为1、2");
    }

    @Override
    @AutoPageAop
    public ResponseInfo getOutsoleOrderDetail(OutsoleOrderDetailReq request) {
        Map<String, Object> map = new HashMap<>();
        String username = UserIdThread.get().getUserName();
        List<OutsoleOrderDetailRep> list = materialMapper.getOutsoleOrderDetail(request, username);
        map.put("list", list);
        BigDecimal qtyTotal = materialMapper.getOutsoleOrderDetailQtyTotal(request, username);
        BigDecimal purQtyTotal = materialMapper.getOutsoleOrderDetailPurQtyTotal(request, username);
        map.put("qtyTotal", qtyTotal);
        map.put("purQtyTotal", purQtyTotal);
        Page<OutsoleOrderDetailRep> page = (Page<OutsoleOrderDetailRep>) list;
        map.put("total", page.getTotal());
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo insertIntoOther(IMaterialIMReq request) {
        String username = UserIdThread.get().getUserName();
        int row = materialMapper.updateIntoMtlPre3(request, username);
        if (row <= 0) {
            return ResponseInfo.error("插入失败请重试");
        }
        return ResponseInfo.ok("插入成功");
    }

    //    1: 生成物料编码 2：置空物料编码 3：形成订购单 4：置空订购单 5：打勾记录删除 6：复制材料信息 //修改材料信息
    @Override
    @Transactional
    public ResponseInfo operateSole(PcSoleOperateReq request) {
        String choose = request.getChoose();
        String username = UserIdThread.get().getUserName();
        String purNo = "BFPM";
        String format = new SimpleDateFormat("yyyyMM").format(new Date());
        purNo = purNo + format;
        RedisAtomicInteger ato = new RedisAtomicInteger(purNo, redisService.getConnectionFactory());
        List<OutsoleOrderDetailRep> list = request.getList();
        list.forEach(x->x.setCompanyId(UserIdThread.get().getCompanyId()));
        switch (choose) {
            case "1":
                for (OutsoleOrderDetailRep rep : list) {
                    //查询当前物料名称是否存在
                    String mtlName = rep.getMtlName();
                    if (mtlName == null ) return ResponseInfo.error("物料名称不能为空");
                    PcOrderMaterToAllRep allRep = new PcOrderMaterToAllRep();
                    allRep.setMtlName(rep.getMtlName());
                    allRep.setMtlUnit(rep.getMtlUnit());
                    allRep.setMtlUnit(rep.getMtlUnit());
                    allRep.setMtlNo("L501");
                    String mtlNo = pcOrderHeadMapping.getMtlNo(allRep);
                    if (mtlNo == null || mtlNo.isEmpty()) {
                        String mtlTypeNo = "L501";
                        BigDecimal no2 = materialMapper.getMtlTypeNo2(mtlTypeNo);
                        BigDecimal add = no2.add(new BigDecimal(1));
                        int i = add.intValue();
                        String mtlNo1 = String.format("%0" + PUT_MTL_LENGTH.getValue() + "d", i);
                        mtlTypeNo = mtlTypeNo + mtlNo1;
                        //将物料编码设置进 mtl_pre_other
                        rep.setMtlNo(mtlTypeNo);
                        materialMapper.setMtlNoInOther(rep, username);
                        rep.setCompanyId(UserIdThread.get().getCompanyId());
                        materialMapper.insertSdMtlNewKf3(rep, username);
                    } else {
                        rep.setMtlNo(mtlNo);
                        materialMapper.setMtlNoInOther(rep, username);
                    }
                }
                return ResponseInfo.ok("物料编码生成成功");
            case "2":
                list.forEach(rep -> {
                    rep.setMtlNo("");
                    materialMapper.setMtlNoInOther(rep, username);
                });
                return ResponseInfo.ok("物料编码置空成功");
            case "3":
                if (request.getVendorName() == null || request.getVendorName().isEmpty()) {
                    return ResponseInfo.error("厂商名称不能为空");
                }
                if (request.getDeliveryDate()==null) return ResponseInfo.error("交期不能为空");
                int increment = ato.incrementAndGet();
                String num = String.format("%0" + PUT_PUR_LENGTH.getValue() + "d", increment);
                purNo += num;
                materialMapper.createSolePurNo(purNo, request, username);
                Map<String, Object> map = new HashMap<>();
                OutsoleOrderDetailReq req = new OutsoleOrderDetailReq();
                req.setPurNo(purNo);
                List<OutsoleOrderDetailRep> lists = materialMapper.getOutsoleOrderDetail(req, username);
                map.put("list", lists);
                map.put("msg","订购单号形成成功");
                return ResponseInfo.ok(map);
            case "4":
                request.setVendorName("");
                request.setVendorName("");
                request.setDeliveryDate(null);
                materialMapper.createSolePurNo("", request, username);
                return ResponseInfo.ok("订购单号置空成功");
            case "5":
                //打勾删除
                materialMapper.deleteFromOther(list, username);
                return ResponseInfo.ok("打勾删除成功");
            case "6":
                //复制材料
                materialMapper.insertMaterial3(list);
                return ResponseInfo.ok("复制材料成功");
            case "7":
                OutsoleOrderDetailRep rep1 = list.get(0);
                OutsoleOrderDetailRep rep2 = list.get(1);
                materialMapper.updateSolePur(rep1, rep2, username);
                return ResponseInfo.ok("修改成功");
            //修改请购数量
            default:
                return ResponseInfo.error("请检查choose参数");
        }
    }

    @Override
    public ResponseInfo mtlHueDesign(String choose, String colorName, Integer pageNum, Integer pageSize) {
        Map<String, Object> map = new HashMap<>();
        List<PcMtlHueDesignRep> list = null;
        if ("1".equals(choose)) {
            list = materialMapper.mtlHueDesign();
        } else {
            PageHelper.startPage(pageNum, pageSize);
            list = materialMapper.mtlColorDesign(colorName);
            Page<PcMtlHueDesignRep> page = (Page<PcMtlHueDesignRep>) list;
            map.put("total", page.getTotal());
        }
        map.put("list", list);
        return ResponseInfo.ok(map);
    }

    //添加色系定义 添加颜色定义 修改色系定义 修改颜色定义 删除色系定义 删除颜色定义
    @Override
    @Transactional
    public ResponseInfo updateHueDesign(PcMtlHueDesignRep rep, String choose, String colorName) {
        String name = UserIdThread.get().getUserName();
        List<PcMtlHueDesignRep> list = null;
        switch (choose) {
            case "1":
                materialMapper.insertHueDesign(rep, name);
                return ResponseInfo.ok("添加成功");
            case "2":
                list = materialMapper.mtlColorDesign(colorName);
                AtomicBoolean bool = new AtomicBoolean(false);
                list.forEach(x -> {
                    rep.getColorCode().equals(x.getColorCode());
                    bool.set(true);
                });
                if (bool.get()) {
                    return ResponseInfo.error("改编号已存在 请重新输入");
                }
                materialMapper.insertColorDesign(rep, name, colorName);
                return ResponseInfo.ok("添加成功");
            case "3":
                list = materialMapper.mtlColorDesign(rep.getColorName());
                if (!list.isEmpty()) {
                    return ResponseInfo.error("该色系下存在颜色");
                }
                materialMapper.updateHueDesign(rep, name);
                return ResponseInfo.ok("修改成功");
            case "4":
                materialMapper.updateColorDesign(rep, name, colorName);
                return ResponseInfo.ok("修改成功");
            case "5":
                list = materialMapper.mtlColorDesign(rep.getColorName());
                if (!list.isEmpty()) {
                    return ResponseInfo.error("该色系下存在颜色定义");
                }
                materialMapper.deleteHueDesign(rep);
                return ResponseInfo.ok("删除成功");
            case "6":
                materialMapper.deleteColorDesign(rep, colorName);
                return ResponseInfo.ok();
            default:
                return ResponseInfo.error("检查choose参数");
        }
    }

    @Override
    public ResponseInfo mtlPropertyListTree() {
        List<SdMtlTypeNewDto> list = materialMapper.getAllMtlProperty();
        List<SdMtlTypeNewDto> rootList = list.stream().filter(x -> x.getParentLevel() == null).collect(Collectors.toList());
        for (SdMtlTypeNewDto dto : rootList) {
            dto.setChildren(getChild(dto.getLevelCode(), list));
        }
        return ResponseInfo.ok(rootList);
    }

    List<SdMtlTypeNewDto> getChild(String id, List<SdMtlTypeNewDto> depts) {
        List<SdMtlTypeNewDto> childList = new ArrayList<>();
        for (SdMtlTypeNewDto dept : depts) {
            if (StringUtil.isNotBlank(dept.getParentLevel())) {
                if (dept.getParentLevel().equals(id)) {
                    childList.add(dept);
                }
            }
        }
        for (SdMtlTypeNewDto dto : childList) {
            dto.setChildren(getChild(dto.getLevelCode(), depts));
        }
        if (childList.size() == 0) {
            return null;
        }
        return childList;
    }

    @Override
    public ResponseInfo insertSdMtlTypeNew(SdMtlTypeNewDto req, String typeNo, String typeName) {
        String parentLevel = req.getLevelCode();
        List<SdMtlTypeNewDto> list = materialMapper.getAllMtlProperty();
        List<SdMtlTypeNewDto> collect = list.stream().filter(x -> x.getTypeNo().equals(typeNo)).collect(Collectors.toList());
        if (collect.size() > 0) {
            return ResponseInfo.error("该分类编码已存在");
        }
        String levelCode = materialMapper.getMaxByCurrentLevel(parentLevel);
        if (levelCode == null) {
            levelCode = parentLevel + "01";
            //不存在设置第一个levelcode 为01
            materialMapper.insertSdMtlTypeNew1(parentLevel, typeNo, typeName, levelCode);
            return ResponseInfo.ok("success");
        }
        //
        BigDecimal bigDecimal = new BigDecimal(levelCode.substring(levelCode.length() - 2));
        BigDecimal add = bigDecimal.add(new BigDecimal("1"));
        int i = add.intValue();
        levelCode = parentLevel + String.format("%0" + SD_MTL_CODE.getValue() + "d", i);
        materialMapper.insertSdMtlTypeNew1(parentLevel, typeNo, typeName, levelCode);
        return ResponseInfo.ok("success");
    }

    @Override
    public ResponseInfo deleteSdMtlTypeNew(SdMtlTypeNewDto req) {
        String levelCode = materialMapper.getMaxByCurrentLevel(req.getLevelCode());
        if (levelCode != null) {
            return ResponseInfo.error("删除失败、当前行下还存在数据");
        }
        materialMapper.deleteSdMtlTypeNew(req);
        return ResponseInfo.ok("删除成功");
    }

    @Override
    public ResponseInfo updateSdMtlTypeNew(SdMtlTypeNewDto req) {
        materialMapper.updateSdMtlTypeNew(req);
        return ResponseInfo.ok("修改成功");
    }

    @Override
    public ResponseInfo sdMtlTypeDetailList(SdMtlTypeDetail req) {
        List<SdMtlTypeDetail> list = materialMapper.sdMtlTypeDetailList(req);
        return ResponseInfo.ok(list);
    }

    @Override
    public ResponseInfo insertSdMtlTypeDetail(SdMtlTypeDetail req) {
        String username = UserIdThread.get().getUserName();
        materialMapper.insertSdMtlTypeDetail(req, username);
        return ResponseInfo.ok("添加成功");
    }

    @Override
    public ResponseInfo mtlPropertyList() {
        Map<String, List> map = new HashMap<>();
        List<Map<String, String>> spec = materialMapper.getSpecs();
        List<Map<String, String>> unit = materialMapper.getUnits();
        List<Map<String, String>> prdType = materialMapper.getPrdTypes();
        List<Map<String, String>> properties = materialMapper.getProperties();
        map.put("spec", spec);
        map.put("unit", unit);
        map.put("prdType", prdType);
        map.put("properties", properties);
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo mtlPropertyRD(String typeName) {
        return ResponseInfo.ok(materialMapper.mtlPropertyRD(typeName));
    }

    @Override
    public ResponseInfo insertProperty(String code, String name, String seqNo, String choose) {
        String username = UserIdThread.get().getUserName();
        switch (choose) {
            case "1":
                materialMapper.insertSdProperty(code, name, username);
                break;
            case "2":
                materialMapper.insertSdSpec(code, name, seqNo, username);
                break;
            case "3":
                materialMapper.insertSdUnit(code, name, username);
                break;
            case "4":
                materialMapper.insertSdPrd(code, name, username);
                break;
            default:
                return ResponseInfo.error("参数错误");
        }
        return ResponseInfo.ok("添加成功");
    }

    @Override
    public ResponseInfo insertPropertyDetail(String mtlName, String seqNo, String spec) {
        materialMapper.insertPropertyDetail(mtlName, seqNo, spec, UserIdThread.get().getUserName());
        return ResponseInfo.ok("添加成功");
    }

    @Override
    public ResponseInfo sdCustTypeAVen(String choose) {
        List<SdCustTypeDto> list = null;
        switch (choose) {
            case "1":
                list = materialMapper.sdCustType();
                break;
            case "2":
                list = materialMapper.sdVenType(UserIdThread.get().getCompanyId());
        }

        List<SdCustTypeDto> returnList = list.stream().filter(x -> x.getParentLevel() == null).collect(Collectors.toList());
        if (returnList.size() <= 0) {
            return ResponseInfo.ok(list);
        }
        for (SdCustTypeDto dto : returnList) {
            dto.setList(setChildList(dto.getLevelCode(), list));
        }
        return ResponseInfo.ok(returnList);
    }

    @Override
    public ResponseInfo insertSdCustType(SdCustTypeDto req, String parentLevel, String choose) {
        String code = null;
        switch (choose) {
            case "1":
                List<SdCustTypeDto> list = materialMapper.sdCustType();
                List<SdCustTypeDto> collect = list.stream().filter(x -> x.getTypeNo().equals(req.getTypeNo())).collect(Collectors.toList());
                if (!collect.isEmpty()) {
                    return ResponseInfo.error("该分类名称已存在");
                }
                if (parentLevel == null || parentLevel.isEmpty()) {
                    code = materialMapper.getVenTypeByPL(parentLevel);
                    BigDecimal bigDecimal = new BigDecimal(code);
                    BigDecimal add = bigDecimal.add(new BigDecimal(1));
                    materialMapper.insertSdCustType(req, add.toString(), parentLevel);
                    break;
                }
                //查询当前节点下是否含有数据
                String max = materialMapper.getSdcustTypeByPL(parentLevel);
                String levelCode = getString(parentLevel, max);
                materialMapper.insertSdCustType(req, levelCode, parentLevel);
                break;
            case "2":
                List<SdCustTypeDto> lists = materialMapper.sdVenType(UserIdThread.get().getCompanyId());
                List<SdCustTypeDto> collects = lists.stream().filter(x -> x.getTypeNo().equals(req.getTypeNo())).collect(Collectors.toList());
                if (!collects.isEmpty()) {
                    return ResponseInfo.error("该分类名称已存在");
                }
                if (parentLevel == null || parentLevel.isEmpty()) {
                    code = materialMapper.getVenTypeByPL(parentLevel);
                    BigDecimal bigDecimal = new BigDecimal(code);
                    BigDecimal add = bigDecimal.add(new BigDecimal(1));
                    req.setCompanyId(UserIdThread.get().getCompanyId());
                    materialMapper.insertVen(req, add.toString(), parentLevel);
                    break;
                }
                String venMax = materialMapper.getVenTypeByPL(parentLevel);
                String venLevelCode = getString(parentLevel, venMax);
                req.setCompanyId(UserIdThread.get().getCompanyId());
                materialMapper.insertVen(req, venLevelCode, parentLevel);
                break;
        }
        return ResponseInfo.ok("添加成功");
    }

    @Override
    public ResponseInfo deleteSdCustOrVen(SdCustTypeDto req, String choose) {
        switch (choose) {
            case "1":
                materialMapper.deleteSdCust(req);
                break;
            case "2":
                materialMapper.deleteSdVen(req);
                break;
        }
        return ResponseInfo.ok("删除成功");
    }

    @NotNull
    private String getString(String parentLevel, String max) {
        String levelCode = null;
        if (max == null || max.isEmpty()) {
            levelCode = parentLevel + "01";
            return levelCode;
        }
        BigDecimal bigDecimal = new BigDecimal(max.substring(max.length() - 2));
        BigDecimal add = bigDecimal.add(new BigDecimal("1"));
        int i = add.intValue();
        levelCode = parentLevel + String.format("%0" + SD_MTL_CODE.getValue() + "d", i);
        return levelCode;
    }

    private List<SdCustTypeDto> setChildList(String levelCode, List<SdCustTypeDto> list) {
        List<SdCustTypeDto> childList = new ArrayList<>();
        for (SdCustTypeDto sdCustTypeDto : list) {
            if (StringUtil.isNotBlank((sdCustTypeDto.getParentLevel()))) {
                if (levelCode.equals(sdCustTypeDto.getParentLevel())) {
                    childList.add(sdCustTypeDto);
                }
            }
        }
        for (SdCustTypeDto sdCustTypeDto : childList) {
            sdCustTypeDto.setList(setChildList(sdCustTypeDto.getLevelCode(), list));
        }
        if (childList.isEmpty()) {
            return null;
        }
        return childList;
    }

    @Override
    @AutoPageAop
    public ResponseInfo sdMtlNewList(SdMtlNewReq req) {
        Map<String, Object> map = new HashMap<>();
        List<SdMtlNew> list = materialMapper.sdMtlNewList(req);
        Page<SdMtlNew> page = (Page<SdMtlNew>) list;
        map.put("list", list);
        map.put("total", page.getTotal());
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo createSdMtlNew(SdMtlNew req, String choose) {
        String typeNo = materialMapper.getTypeNoByName(req.getTypeName());
        SdMtlNewReq sdMtlNewReq = new SdMtlNewReq();
        switch (choose) {
            case "1":
                sdMtlNewReq.setMtlName1(req.getMtlName());
                sdMtlNewReq.setMtlUnit(req.getMtlUnit());
                sdMtlNewReq.setMtlSpec2(req.getMtlSpec());
                sdMtlNewReq.setTypeName(req.getTypeName());
                List<SdMtlNew> sdMtlNews = materialMapper.sdMtlNewList(sdMtlNewReq);
                if (!sdMtlNews.isEmpty()) {
                    SdMtlNew sdMtlNew = sdMtlNews.get(0);
                    req.setMtlNo(sdMtlNew.getMtlNo());
                    return ResponseInfo.ok(req);
                }
                //当前分类编码的最大值存放在redis自增序列里面
                //使用typeNo作为redis自增的key
                String autoNum = null;
                Set scan = redisService.scan(typeNo);
                if (scan.size() <= 0) {
                    RedisAtomicInteger ato = new RedisAtomicInteger(typeNo, redisService.getConnectionFactory());
                    Integer num = materialMapper.getMaxByTypeNo(typeNo);
                    ato.set(num);
                }
                Integer i = Integer.valueOf(redisService.get(typeNo));
                autoNum = String.format("%0" + MTL_NO_LENGTH.getValue() + "d", ++i);
                String mtlNo = typeNo += autoNum;
                req.setMtlNo(mtlNo);
                return ResponseInfo.ok(req);
            case "2":
                List<SdMtlNew> list = materialMapper.sdMtlNewList(sdMtlNewReq);
                List<SdMtlNew> collect = list.stream().filter(x -> x.getMtlNo().equals(req.getMtlNo())).collect(Collectors.toList());
                if (!collect.isEmpty()) {
                    return ResponseInfo.error("这条编码已存在");
                }
                RedisAtomicInteger ato = new RedisAtomicInteger(typeNo, redisService.getConnectionFactory());
                req.setCompanyId(UserIdThread.get().getCompanyId());
                materialMapper.insertSdMtlNew(req, UserIdThread.get().getUserName());
                ato.incrementAndGet();
                return ResponseInfo.ok("插入成功");
            case "3":
                materialMapper.updateSdMtlNew(req, UserIdThread.get().getUserName());
                return ResponseInfo.ok();
            case "4":
                materialMapper.deleteSdMtlNew(req);
                return ResponseInfo.ok("删除成功");
            default:
                return null;
        }
    }

    @Override
    public void downMtlPurSlipExcel(String slipNo, HttpServletResponse response) throws IOException, WriterException {
        setResponse(response);
        Map<String, Object> map = new HashMap<>();
        ByteArrayOutputStream outputStream = QRCodeGenerator.generateQRCodeToStream(slipNo, 130, 90);
        byte[] array = outputStream.toByteArray();
        PcOrderMaterialOrderDetailRequest request = new PcOrderMaterialOrderDetailRequest();
        request.setPurNo(slipNo);
        request.setChoose("0");
        //TODO 后续考虑是否是导出同一个人生成的物料编码
        String name = UserIdThread.get().getUserName();
        String vendor = null;
        List<PcOrderMaterialOrderDetailRep> list = materialMapper.pcOrderMtlMakeOrderDetail(request, "");
        if (list.isEmpty()) {
            return;
        }
        Integer i = 1;
        Double money = 0.d;
        for (PcOrderMaterialOrderDetailRep rep : list) {
            vendor = rep.getVendorName();
            rep.setPurQty(new BigDecimal(rep.getPurQty()).stripTrailingZeros().toPlainString());
            String mtlColor = rep.getMtlColor()==null?"":rep.getMtlColor();
            rep.setMtlName(mtlColor+""+rep.getMtlName());
            rep.setSeqNo(i++);
            money += Double.parseDouble(rep.getPurQty());
        }
        map.put("list", list);
        PcOrderMaterialOrderDetailRep rep = list.get(0);
        map.put("slipNo", slipNo);
        map.put("purType", rep.getType());
        map.put("vendorName", rep.getVendorName());
        map.put("brand",rep.getBrand());
        map.put("style",rep.getStyle());
        map.put("custStyle",rep.getCustStyle());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String purDate = "";
        String jGDate = "";
        if (rep.getPurDate() != null) {
            purDate = format.format(rep.getPurDate());
        }
        if (rep.getDeliveryDate() != null) {
            jGDate = format.format(rep.getDeliveryDate());
        }
        map.put("purDate", purDate);
        map.put("deliveryDate", jGDate);
        map.put("money", new BigDecimal(money).stripTrailingZeros().toPlainString());
        map.put("photo", array);
        map.put("name", name);
        ExcelPoiUtils.writeExcelWithPictureToResponse(response,"templates/材料采购单.xls",map,array,13,14,0,2,vendor+"_"+DateUtils.dateTimeNow()+".xls",2,3,3,10,12,4,0);
    }

    @Override
    public void downUniversalExcel(String slipNo, HttpServletResponse response) throws IOException, WriterException {
        String name = UserIdThread.get().getUserName();
        setResponse(response);
        Map<String, Object> map = new HashMap<>();
        ByteArrayOutputStream outputStream = QRCodeGenerator.generateQRCodeToStream(slipNo, 130, 90);
        byte[] array = outputStream.toByteArray();
        MaterialDetail1Request request = new MaterialDetail1Request();
        request.setPurNo(slipNo);
        List<PcOrderMaterToAllRep> list = materialMapper.getMaterialADetail1(request, "");
        map.put("list", list);
        map.put("name", name);
        map.put("slipNo", slipNo);
        int seqNo = 1;
        String vendorName = "";
        if (!list.isEmpty()) {
            BigDecimal total = new BigDecimal(0);
            for (PcOrderMaterToAllRep rep : list) {
                rep.setPurQty(new BigDecimal(rep.getPurQty()).stripTrailingZeros().toPlainString());
                String mtlColor = rep.getMtlColor()==null?"":rep.getMtlColor();
                rep.setMtlName(mtlColor+""+rep.getMtlName());
                rep.setSeqNo(seqNo++);
                BigDecimal purQty = rep.getPurQty()==null?new BigDecimal(0):new BigDecimal(rep.getPurQty());
                total = total.add(purQty);
            }
            PcOrderMaterToAllRep rep = list.get(0);
            vendorName = rep.getVendorName();
            map.put("total", total.stripTrailingZeros().toPlainString());
            map.put("vendorName", rep.getVendorName());
            map.put("purType", rep.getPurType());
            String purDate = "";
            String deliveryDate = "";
            setDate(rep, purDate, deliveryDate, map);
        }
        ExcelPoiUtils.writeExcelWithPictureToResponse(response,"templates/通用材料采购单.xls",map,array,10,11,0,3,"通用材料采购单_"+vendorName+""+DateUtils.dateTimeNow()+".xls",2,3,3,8,10,4,3);
    }

    @Override
    public void downloadSoleOrder(HttpServletResponse response, String slipNo) throws IOException, WriterException {
        Map<String, Object> map = new HashMap<>();
        OutsoleOrderDetailReq req = new OutsoleOrderDetailReq();
        req.setPurNo(slipNo);
        List<OutsoleOrderDetailRep> reps = materialMapper.getOutsoleOrderDetail(req, "");
        AtomicReference<Integer> i = new AtomicReference<>(1);
        reps.forEach(x -> x.setSeqNo(i.getAndSet(i.get() + 1)));
        byte[] array = QRCodeGenerator.generateQRCodeToStream(slipNo, 120, 90).toByteArray();
        BigDecimal total = new BigDecimal(0);
        for (OutsoleOrderDetailRep rep : reps) {
            if (rep.getMtlUnit()==null) rep.setMtlUnit("双");
            rep.setPurQty(new BigDecimal(rep.getPurQty()).stripTrailingZeros().toString());
            total = total.add(new BigDecimal(rep.getPurQty()));
        }
        map.put("list", reps);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        OutsoleOrderDetailRep rep = reps.get(0);
        map.put("vendorName", rep.getVendorName());
        map.put("moldNo", rep.getMoldNo());
        map.put("brand", rep.getBrand());
        if (rep.getPurDate() != null ) {
            map.put("purDate", format.format(rep.getPurDate()));
        }
        map.put("slipNo", slipNo);
        map.put("purType", rep.getPurType());
        map.put("style", rep.getStyle());
        map.put("name", UserIdThread.get().getUserName());
        if (rep.getDeliveryDate() != null) {
            map.put("deliveryDate", format.format(rep.getDeliveryDate()));
        }
        map.put("total", total.stripTrailingZeros());
        String outName = rep.getVendorName() + "出货单_" + slipNo+".xls";
        ExcelPoiUtils.writeExcelWithPictureToResponse(response, "templates/大底订购作业模板.xls", map, array, 12, 13, 0, 3, outName,2,3,3,8,10,4,0);
    }

    @Override
    public void downloadSdMtlNew(HttpServletResponse response, SdMtlNewReq req) throws IOException {
        List<SdMtlNew> list = materialMapper.sdMtlNewList(req);
        ExcelUtils.creatByTemplate(response,"开发材料汇总表模板.xls","开发材料汇总表_"+DateUtils.dateTimeNow(),list);
    }

    private static void setDate(PcOrderMaterToAllRep rep, String purDate, String deliveryDate, Map<String, Object> map) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        if (rep.getPurDate() != null) {
            purDate = format.format(rep.getPurDate());

        }
        if (rep.getDeliveryDate() != null) {
            deliveryDate = format.format(rep.getDeliveryDate());
        }
        map.put("purDate", purDate);
        map.put("deliveryDate", deliveryDate);
    }

    public static void setResponse(HttpServletResponse response) {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + "x" + ".xlsx");
    }
}
